package com.gss.module.generator.core;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.gss.common.utils.StringUtils;
import com.gss.module.generator.constants.CommonConstants;
import com.gss.module.generator.entity.BaseEntity;

import java.util.Date;

/**
 * @author DYang
 * @date 2023/5/30
 * 构建service
 */
public class ServiceGenerator {

    private static  String SERVICE_PATH = "classpath:template/ServiceGeneratorTemplate.template";

    /**
     * 根据内如构建实体类
     * @param fileDir
     * @param baseEntity
     */
    public static void builder(String fileDir,BaseEntity baseEntity){
        //构建实体类
        String content = buildService(baseEntity,SERVICE_PATH);
        if (content == null){
            System.out.println("模板不存在，暂未解析到数据");
            return;
        }
        //存储到指定指定文件
        saveEntityFile(content,baseEntity.getClassName(),fileDir);
    }

    /**
     * 将数据写道指定文件
     * @param content
     * @param className
     * @param fileDir
     */
    private static void saveEntityFile(String content,String className,String fileDir) {
        fileDir = fileDir + "/I" + className + "Service" + CommonConstants.JAVA_FILE;
        FileUtil.writeString(content, fileDir, "UTF-8");
    }

    /**
     * 构建实体类
     * @param baseEntity
     * @param filePath
     * @return
     */
    private static String buildService(BaseEntity baseEntity, String filePath) {
        String content = ResourceUtil.readUtf8Str(filePath);
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        content = content.replace("${AUTHOR}",baseEntity.getAuthor());
        content = content.replace("${DATE}", DateUtil.format(new Date(),"yyyy/MM/dd"));
        content = content.replace("${CLASS_NAME}",baseEntity.getClassName());
        return content;
    }

}
